# from multiprocessing import Pool
from pymongo import MongoClient
# from snownlp import SnowNLP
from time import sleep
from PIL import Image
import string
import signal
# import re
import time
import sys
import os

def signal_handler(signal, frame):
    os.system("adb shell rm /sdcard/screenshot.png >nul 2>&1")
    sys.exit(0)

def scapocr(char) :

    # os.system("adb exec-out screencap -p > l.temp.0.png") ; open('l.temp.png', 'wb').write(open('l.temp.0.png', 'rb').read().replace(b'\r\n',b'\n')) # over Android 6
    # os.system("adb shell screencap -p /sdcard/screenshot.png && adb pull /sdcard/screenshot.png real.temp.png") # under Android 6
    
    Image.open('real.temp.png').crop((50,250,670,1200)).save('l.%s.png' %'{:04}'.format(i) ,'PNG') # Sumsang
    # Image.open('real.temp.png').crop((0,150,720,1440)).save('l.%s.png' %'{:04}'.format(i),'PNG') # Redmi 6a
    # Image.open('real.temp.png').crop((50,300,670,1200)).save('l.%s.png' %'{:04}'.format(i),'PNG') # Redmi 4x
    
    os.system("tesseract real.temp.png real.temp --dpi 300 -l chi_sim makebox >nul 2>&1")
    boxcontext = open('real.temp.box', mode='r', encoding='UTF8').read()

    context = ''.join(re.split(r' .+\n', boxcontext))

    MongoClient()['db']['5-19'].find_many({'Q':{$regex: '^%s' %context[:5] }})


    tartemp = tuple(map(int, re.search(char.replace('',' (.+) 0\n')[8:], context)[1].split(' ')))
    














# open('l.txt', mode='r', encoding='UTF8').writelines('## %s\n\n' %'{:04}'.format(i))

queue = ''
lastqueue = ''                                                      # 去重
repl = string.punctuation+'“”、，。 《》°'         # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

for line in open('l.txt', mode='r', encoding='UTF8') :
    
    if line.startswith('##') :
        queue = queue.translate(str.maketrans('','', repl))
        if not ( queue.isspace() or queue == '' ) :
            if queue[:5] == lastqueue[:5] : queue = '' ; continue   # 去重
            lastqueue = queue                                       # 去重
            
            print(queue[:-1])

            ans = input('? ans>')

            MongoClient()['db']['5-19'].insert_one({'Q':queue[:-1], 'A':ans})
            # MongoClient()['db']['temp'].insert_one( {'l2': '%s' %queue[:2], 'l4': '%s' %queue[:4], 'bk':'%s' %queue[queue.find('《') : queue.find('》')], 'ans':'%s' %ans} )
            
        queue = ''
        continue

    queue = queue+line[:-1]


def main() :

    print('Realtime device>img>context>ans>touch-area')
    
    os.system("adb devices")
